package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author 黑马程序员
 */
@RestController
@RequestMapping("/address")
public class AddressController {


    @Reference
    private AddressService addressService; // com.itheima.service.AddressService

    /**
     * 新增检查项
     *
     * @param Address
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("新增检查项")
    public Result add(@RequestBody Address Address) {
        try {
            addressService.add(Address);
            return new Result(true, MessageConstant.ADD2);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD1);
        }
    }

    /**
     * 分页查询检查项数据
     *
     * @param queryPageBean
     * @return
     */
    @GetMapping("/findPage")
    @ApiOperation("分页查询检查项")
    public Result findPage(QueryPageBean queryPageBean) {
        try {
            PageResult pageResult = addressService.pageQuery(queryPageBean);
            return new Result(true, MessageConstant.GET1, pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.GET2);
        }
    }

    /**
     * 根据id删除检查项
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation("根据ID删除检查项")
    public Result deleteById(@PathVariable Integer id) {
        try {
            //删除检查项
            addressService.deleteById(id);
            return new Result(true, MessageConstant.DELETE1);
        } catch (RuntimeException e) {
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE2);
        }
    }
    /**
     * 查询所有检查项数据
     *
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        try {
            List<Address> items = addressService.findAll();
            return new Result(true, MessageConstant.GET1, items);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET2);
        }
    }
}
